package com.transaction.utils;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	
	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
	
	//超时时间毫秒
	private static int timeOut = 9000;

	/**
	 * 获取url返回的内容
	 * @param targetUrl http url
	 * @return
	 */
	public static String doGet(String targetUrl){
		
		URL url = null;
		HttpURLConnection conn = null;
		StringBuffer sResult = new StringBuffer();
		BufferedReader in = null;
		try {
			url = new URL(targetUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(30000);
			conn.connect();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String sCurrentLine = null;
			while ((sCurrentLine = in.readLine()) != null) {
				sResult.append(sCurrentLine.trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sResult.toString();
	}
	
	/**
	 * 获取302跳转的url
	 * @param targetUrl
	 * @param timeout
	 * @return
	 */
	public static String doGet302(String targetUrl, int timeout){
		
		URL url = null;
		HttpURLConnection conn = null;

		StringBuffer sResult = new StringBuffer();
		BufferedReader in = null;
		try {
			url = new URL(targetUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setInstanceFollowRedirects(false);
			conn.setConnectTimeout(timeout * 1000);
			conn.connect();
			if(conn.getResponseCode()==302||conn.getResponseCode()==301){
				sResult.append(conn.getHeaderField("Location"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sResult.toString();
	}
	
	/**
	 * 获取302跳转的url
	 * @param targetUrl
	 * @param timeout
	 * @return
	 */
	public static String doGet302(String targetUrl, int timeout,String ref){
		
		URL url = null;
		HttpURLConnection conn = null;

		StringBuffer sResult = new StringBuffer();
		BufferedReader in = null;
		try {
			url = new URL(targetUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			if(ref!=null &&ref.length()>0){
				conn.setRequestProperty("Referer", ref); 
				
			}
			conn.setRequestProperty("user-agent", "Mozilla/5.0 (Linux; U; Android 2.2; zh-cn; HTC Desire Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
			conn.setInstanceFollowRedirects(false);
			conn.setConnectTimeout(timeout * 1000);
			conn.connect();
			if(conn.getResponseCode()==302||conn.getResponseCode()==301){
				sResult.append(conn.getHeaderField("Location"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sResult.toString();
	}
	
	public static String doPosts(String uri,String content) {

        try {
            //创建连接
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
			connection.setReadTimeout(1000000);
            connection.setRequestProperty("Content-Type",
                    "application/octet-stream");
            connection.setRequestProperty("Connection", "Close");

            //POST请求
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());

            out.writeBytes(content);
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	
    
    public static String doPost(String uri,String content) {

        try {
            //创建连接
            URL url = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
			connection.setReadTimeout(1000000);
            connection.setRequestProperty("Content-Type",
                    "application/json;charset=utf-8");
            connection.setRequestProperty("Connection", "Close");

            //POST请求
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());

            out.writeBytes(content);
            out.flush();
            out.close();
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
